package com.app.action.concurrent;

import java.util.concurrent.Exchanger;

public class ExchangerAction {

    public static void main(String[] args) {
        Exchanger exchanger = new Exchanger();
        new Thread(new ExchangerWorkRunnable(exchanger, 10)).start();
        new Thread(new ExchangerWorkRunnable(exchanger, 100)).start();

    }
}

class ExchangerWorkRunnable implements Runnable {
    private Exchanger exChanger;
    private int count = 0;

    public ExchangerWorkRunnable(Exchanger exchanger, int count) {
        this.exChanger = exchanger;
        this.count = count;
    }

    @Override
    public void run() {
        try {
            Thread.sleep((long) (Math.random() * 30 * 1000));
            System.out.println("----" + Thread.currentThread().getName() + "-----start exchanger:" + count);
            int result = (Integer) exChanger.exchange(count);
            System.out.println("----" + Thread.currentThread().getName() + "------after changed:" + result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

